<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="系部" prop="college">
        <el-input
          v-model="queryParams.college"
          placeholder="请输入系部"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="advancedStatus">
        <el-select
          v-model="queryParams.advancedStatus"
          placeholder="请选择"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.advanced_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="goApply"
          v-hasPermi="['eqxm:team:add']"
        >申请先进个人</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="info"
          v-hasPermi="['eqxm:advanced:applystu']"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport(1)"
          >学生申请</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          v-hasPermi="['eqxm:advanced:applyteach']"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport(2)"
          >教师申请</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="团队名称" align="center" prop="teamName" />
      <el-table-column label="系部" align="center" prop="college" />
      <el-table-column label="调研主题" align="center" prop="researchTopic" />
      <el-table-column label="个人总结" align="center" class-name="small-padding fixed-width">
	   <template slot-scope="scope">
			  <el-button
			    size="mini"
			    type="text"
			    icon="el-icon-edit"
			    @click="handleDownload(scope.row)"
			  >查看</el-button>
	   </template>
	 </el-table-column>
      <el-table-column label="实打/应打" align="center" prop="clockCount">
        <template slot-scope="scope">
          <span>{{ scope.row.actualClock }}/{{ scope.row.shouldClock }}</span>
        </template>
      </el-table-column>
      <a href=""></a
      ><el-table-column label="状态" align="center" prop="advancedStatus">
        <template slot-scope="scope">
          <!-- 默认0待审核，1审核通过，2审核拒绝，3推荐 4.颁奖-->
          <dict-tag :options="dict.type.advanced_status" :value="scope.row.advancedStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" v-if="scope.row.advancedStatus==0 || scope.row.advancedStatus==2" type="text" icon="el-icon-edit" :disabled="scope.row.username !== name" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改团队对话框 -->
    <!--    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog> -->

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-select
        v-model="upload.teamId"
        placeholder="实践团队"
        clearable
        size="small"
        style="width: 240px"
      >
        <el-option v-for="dict in teamOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
      </el-select>

      <el-upload
        ref="upload"
        action=""
        accept=".doc,.docx,.xls,.xlsx,.txt"
        :file-list="upload.fileList"
        :limit="1"
        :on-progress="handleFileUploadProgress"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-remove="handleFileRemove"
        :before-remove="beforeRemove"
        :on-change="fileChange"
        :auto-upload="false"
        :headers="upload.headers"
        :disabled="upload.isUploading"
      >
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">
          只能上传doc、docx、xls、xlsx、txt文件,且大小不能超过35MB
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTeam, getTeam, delTeam, addTeam, updateTeam, exportTeam } from '@/api/eqxm/team';
import {
  listTeamStudent,
  getTeamStudent,
  delTeamStudent,
  addTeamStudent,
  updateTeamStudent,
  exportTeamStudent,
  listAdvanced,
  importTemplate,
  getUserTeam,
  applyAdvanced,
} from '@/api/eqxm/teamStudent';
import { getToken } from '@/utils/auth';
import CommonUtils from '@/utils/CommonUtils';
import { mapGetters } from 'vuex';
export default {
  name: 'Team',
  dicts: ['advanced_status'],
  computed: {
    ...mapGetters(['name', 'userName']),
  },
  components: {},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 团队表格数据
      teamList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        college: null,
        researchTopic: null,
        isimportant: null,
        presentation: null,
        presentationdetail: null,
        transportation: null,
        accommodation: null,
        publicity: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/user/importData',
        teamId: '',
        fileChangeFlag: false,
        fileList: [],
      },
      teamOptions: [],

      applyType: null,
    };
  },
  created() {
    this.getList();
    getUserTeam().then(response => {
      this.teamOptions = response.data;
      if (this.teamOptions.length > 0) {
        this.upload.teamId = this.teamOptions[0].id;
        console.log(this.upload.id, 'teamId');
      }
    });
  },
  methods: {
    /** 查询团队列表 */
    getList() {
      this.loading = true;
      listAdvanced(this.queryParams).then(response => {
        console.log(response.data);
        this.teamList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        delFlag: null,
        college: null,
        createBy: null,
        researchTopic: null,
        isimportant: null,
        createTime: null,
        presentation: null,
        updateBy: null,
        presentationdetail: null,
        updateTime: null,
        transportation: null,
        accommodation: null,
        publicity: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      //清空store的项目信息
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/team/teamManage', //跳转的路径
        query: { type: 0 },
      });
    },
    /** 下载按钮操作 */
	handleDownload(row) {
    window.open(process.env.VUE_APP_BASE_API +`/eqxm/teamStudent/handleDownload/${row.id}/${row.type}`);
  },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.applyType = row.type;
      /* this.reset();
          
      const vm = this
      vm.$router.push({  //核心语句
        path:'/advanced/lookStudent/'+row.id//跳转的路径
      }) */
      this.upload.fileList = [];
      this.upload.id = row.id;
      this.upload.title = '申请先进个人';
      this.upload.open = true;
    },
    upload(row) {
      this.reset();
      let teamInfo = {
        id: row.id,
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/team/upload', //跳转的路径
        query: { type: 0 },
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTeam(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess('修改成功');
                this.open = false;
                this.getList();
              }
            });
          } else {
            addTeam(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess('新增成功');
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除团队编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return delTeam(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有团队数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return exportTeam(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    recommendTeam() {
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/schoolmatch/recommendTeam', //跳转的路径
      });
    },
    judge() {
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/schoolmatch/judge', //跳转的路径
      });
    },
    review() {
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/schoolmatch/review', //跳转的路径
      });
    },
    collegeScore() {
      let teamInfo = {
        id: '',
      };
      CommonUtils.setCurTeamInfo(teamInfo);
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/schoolmatch/collegeScore', //跳转的路径
      });
    },
    goApply() {
      const vm = this;
      vm.$router.push({
        //核心语句
        path: '/advanced/apply', //跳转的路径
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有用户数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return exportUser(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    },
    /** 导入按钮操作 */
    handleImport(type) {
      this.applyType = type;
      this.upload.title = '申请先进个人';
      this.upload.id = this.name;
      this.upload.fileList = [];
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        if (response != undefined || response != null) {
          if (response.data.size > 0) {
            let fileName = decodeURI(response.headers.contentfile);

            let contentType = 'application/x-msdownload;';
            let blob = new Blob([response.data], {
              type: contentType + 'charset=UTF-8',
            });
            if (window.navigator.msSaveOrOpenBlob) {
              //IE10+下载
              navigator.msSaveBlob(blob, fileName);
            } else {
              // 非IE下载
              var link = document.createElement('a');
              link.href = window.URL.createObjectURL(blob);
              link.download = fileName;
              link.click();
              //释放内存
              window.URL.revokeObjectURL(link.href);
            }
          }
        }
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 文件移除时 */
    handleFileRemove(file, fileList) {
      this.upload.fileList = [];
      this.form.rcgcDocumentFileType = '';
    },
    // 文件改变时
    fileChange(file, fileList) {
      this.upload.fileChangeFlag = true;
      this.upload.fileList = fileList;
      //文件改变回填选中文件的类型
      let fileName = file.name;
      let type = fileName.split('.')[fileName.split('.').length - 1];

      this.form.rcgcDocumentFileType = type;
    },
    // 文件移除之前
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`只允许上传单个文件，请先删除已上传的文件！`);
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error('上传失败, 请重试');
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      this.upload.isUploading = false;
      this.$message.success('上传成功');
      this.$emit('input', res.url);
    },
    // 获取文件名称
    getFileName(name) {
      if (name.lastIndexOf('/') > -1) {
        return name.slice(name.lastIndexOf('/') + 1).toLowerCase();
      } else {
        return '';
      }
    },
    /** 提交按钮 */
    submitFileForm() {
      console.log(this.upload, 'this.upload');
      if (this.upload.fileList == null || this.upload.fileList.length <= 0) {
        this.$modal.msgError('请上传文件模板');
        return;
      }
      let fileSize = this.upload.fileList[0].size / (1024 * 1024);
      if (fileSize > 35) {
        this.$modal.msgError('上传文件过大，请重新选择文件上传');
        return false;
      }
      var testmsg = this.upload.fileList[0].name.substring(
        this.upload.fileList[0].name.lastIndexOf('.') + 1
      );
      const extension = testmsg === 'xls';
      const extension2 = testmsg === 'xlsx';
      const extension3 = testmsg === 'doc';
      const extension4 = testmsg === 'docx';
      const extension5 = testmsg === 'txt';
      // const isLt2M = file.size / 1024 / 1024 < 10
      if (!extension && !extension2 && !extension3 && !extension4 && !extension5) {
        this.$message({
          message: '只能上传doc、docx、xls、xlsx格式的文件!',
          type: 'warning',
        });
        return false;
      }

      let formData = new FormData();
      this.upload.fileList.forEach(file => {
        formData.append('file', file.raw);
      });
      formData.append('teamId', this.upload.teamId);
      formData.append('type', this.applyType);
      // formData.append("id", this.upload.id);
      applyAdvanced(formData).then(response => {
        this.$modal.msgSuccess('申请成功');
        this.upload.open = false;
        this.getList();
      });
    },
  },
};
</script>
